<template>
	<view>
		<el-form ref="form" v-if="formData && field" :model="formData" :rules="rules" label-width="120px">
			<el-divider content-position="left">基础信息</el-divider>
			<el-row>
				<el-col :span="8" v-for="(meta, _index) in field" :key="_index">
					<form-item :formData="formData" :meta="meta"></form-item>
				</el-col>
			</el-row>
			<template v-if="extendMeta && extendMeta.length > 0">
				<el-divider content-position="left">扩展信息</el-divider>
				<el-row>
					<el-col :span="8" v-for="(meta, _index) in extendMeta" :key="_index">
						<form-item :formData="formData" :meta="meta"></form-item>
					</el-col>
				</el-row>
			</template>
			<view class="uni-button-group">
				<button style="width: 100px;" type="primary" class="uni-button"
					@click="submit">{{$t('common.button.submit')}}</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;"><button style="width: 100px;"
						class="uni-button">{{$t('common.button.back')}}</button></navigator>
			</view>
		</el-form>
	</view>
</template>

<script>
	import ToolAction from "@/tool/http/tool-action.js";
	import extension from "@/pages/common/extension.js";
	import FormItem from "./form-item.vue";

	let api;

	let ruleConfig;

	export default {
		components: { FormItem },
		props: {
			dataId: {
				type: String,
				default: undefined
			},
			dataCode: {
				type: String,
				require: true
			},
			dsId: {
				type: String,
				default: undefined
			}
		},
		data() {
			return {
				formData: undefined,
				metadata: [],
				extendMeta: []
			}
		},
		computed: {
			field() {
				return [...this.metadata.filter(item => !item.hidden && ruleConfig.extendField !== item.name), ...ruleConfig
					.extendFields];
			},
			rules() {
				let rules = {};
				// this.field.forEach(item => {
				// 	rules[item.name] = []
				// });
				return rules;
			}
		},
		mounted() {
			api = ToolAction.init(this.dataCode, this.dsId);
			this.init();
		},
		watch: {
			formData: {
				deep: true,
				handler(watchForm) {
					if (!ruleConfig) return;
					// this.extendMeta = [];
					this.$nextTick(() => {
						this.extendMeta = ruleConfig.formOnChange(watchForm) || [];
					})
				}
			}
		},
		methods: {
			async init() {
				await this.loadMetaData();
				await this.loadView();
				initForm(this.formData);
				// this.formData = {};
			},
			async loadMetaData() {
				let res = await api.meta()
				ruleConfig = await extension.init(this.dataCode, res, this.dsId);
				this.metadata = res;
				// this.metadata.forEach(item => {
				// 	if (!this.formData[item.name] && this.formData[item.name] !== false && item.dictList) {
				// 		// this.formData[item.name] = item.dictList ? [] : undefined;
				// 	}
				// })
			},
			submit() {
				this.$refs.form.validate((valid, fields) => {
					if (!valid) {
						return;
					}
					api.sync({
						...onFormSubmit(this.formData),
						id: this.dataId
					}).then(res => {
						this.$toolUni.toast('修改成功');
						uni.$emit('commonLoadData');
						setTimeout(() => uni.navigateBack(), 200)
					})
				})
			},
			async loadView() {
				if (!this.dataId) { this.formData = {}; return; }
				this.formData = await api.view({ id: this.dataId });
			}
		}
	}

	function initForm(form = {}) {
		let extendVal = form[ruleConfig.extendField];
		if (extendVal) {
			Object.keys(extendVal).forEach(key => {
				form["__" + key] = extendVal[key]
			})
		}
	}

	function onFormSubmit(formOrigin = {}) {
		formOrigin = {
			...formOrigin
		}
		const extendObj = {}
		// 扩展数据转换
		Object.keys(formOrigin).filter(item => item.startsWith('__')).forEach(item => {
			extendObj[item.substr(2)] = formOrigin[item]
			delete formOrigin[item]
		})
		// 临时数据清理
		Object.keys(formOrigin).filter(item => item.startsWith('_')).forEach(item => {
			delete formOrigin[item]
		})
		if (Object.keys(extendObj).length) {
			formOrigin[ruleConfig.extendField] = JSON.stringify(extendObj)
		}
		return formOrigin;
	}
</script>

<style scoped>
</style>
